<?php

namespace App\Http\Controllers\Admin;

use App\Models\Permission;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PermissionsController extends Controller
{
    public function index(){
        $permissions = Permission::paginate(PAGE_NUM);

        return view('admin.permissions.index', compact('permissions'));
    }

    public function create(){
        return view('admin.permissions.create');
    }

    public function store(Request $request){
      if(preg_match("/[\x7f-\xff]/", $request->qxname)){
        exit(json_encode(array('code'=>0,'msg'=>'权限名称不能为汉字')));
      }
        $this->validate($request, [
            'qxname' => 'required|max:50|unique:permissions,name|alpha_num',
            'display_name'=>'required|min:2|max:6|alpha_dash',
            'description'=>'max:10'
        ]);
        $request->qxname = trim(str_replace(" ","",$request->qxname)," ");
        $request->display_name = trim(str_replace(" ","",$request->display_name)," ");
        $permission = Permission::create([
          'name'=>$request->qxname,
          'display_name'=>$request->display_name,
          'description'=>$request->description
        ]);
        if($permission){
            exit(json_encode(array('code'=>1, 'url'=>'/admin/permissions')));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>$permission)));
        }
    }

    public function edit($id){
        $perm = Permission::findOrFail($id);
        return view('admin.permissions.edit', compact('perm'));
    }

    public function update(Request $request, $id){
      if(preg_match("/[\x7f-\xff]/", $request->qxname)){
        exit(json_encode(array('code'=>0,'msg'=>'权限名称不能为汉字')));
      }
        $perm = Permission::findOrFail($id);
        $this->validate($request, [
          'qxname' => 'required|max:50|unique:permissions,name|alpha_num',
          'display_name'=>'required|min:2|max:6|alpha_dash',
          'description'=>'max:10'
        ]);
        $request->qxname = trim(str_replace(" ","",$request->qxname)," ");
        $request->display_name = trim(str_replace(" ","",$request->display_name)," ");
        $result = $perm->update($request->all());
        if($result){
            exit(json_encode(array('code'=>1, 'url'=>'/admin/permissions')));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>$result)));
        }
    }

    public function destroy($id){
        $role = Permission::findOrFail($id);
        if ($role->delete()){
            exit(json_encode(array('code'=>1)));
        } else {
            exit(json_encode(array('code'=>0)));
        }
    }
}
